package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    @ExceptionHandler
    public Result exceptionHandler(Exception ex){
        log.error("异常信息：{}", ex.getMessage());
        String message = ex.getMessage();
        // 如果异常信息中包含“Duplicate entry”则返回用户名已存在(重名)
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2].substring(0, split[2].lastIndexOf("'"));
            return Result.error("您输入的用户名"+username + "已存在，请修改后添加！");
        }
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获路径异常
     */

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> httpRequestMethodNotSupportedExceptionHandler(HttpServletRequest request,HttpRequestMethodNotSupportedException ex) {
        log.info("请求开始 ===> {} {} from {}",
                request.getMethod(),
                request.getRequestURI(),
                request.getRemoteAddr());
        log.debug("请求参数: {}", request.getParameterMap());
        return Result.error(ex.getMessage());
    }
}
